package com.thxr.sso.server.service.impl;

import java.util.List;

import com.thxr.sso.server.mapper.UserMapper;
import com.thxr.sso.server.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thxr.sso.client.rpc.Result;
import com.thxr.sso.client.rpc.RpcUser;
import com.thxr.sso.server.service.UserService;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	//仿制用户名密码
	/*private static List<User> userList;
	static {
		userList = new ArrayList<>();
		userList.add(new User(1, "管理员", "admin", "123456"));
	}
	
	@Override
	public Result<RpcUser> login(String account, String password) {
		for (User user : userList) {
			if (user.getAccount().equals(account)) {
				if(user.getPassword().equals(password)) {
					return Result.createSuccess(new RpcUser(user.getId(), user.getAccount()));
				}
				else {
					return Result.createError("密码有误");
				}
			}
		}
		return Result.createError("用户不存在");
	}*/

	@Override
	public Result<RpcUser> login(String account, String password) {

		if (account==null || account.trim().length()==0) {
			return Result.createError("请输入用户名");
		}
		if (password==null || password.trim().length()==0) {
			return Result.createError("请输入密码");
		}

		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("account", account);
		List<User> userList = userMapper.selectByExample(example);
		// true user
		if (userList == null || userList.size() == 0){
			return Result.createError("用户名或密码错误");
		}
		User user = userList.get(0);
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())){
			return Result.createError("用户名或密码错误");
		}
		//用户名和密码正确
		//return new Result<User>(user);
		return Result.createSuccess(new RpcUser(user.getId(), user.getAccount()));
	}

	@Override
	public Result findByAccount(String account) {
		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("account", account);
		List<User> userList = userMapper.selectByExample(example);

		if (userList == null || userList.size() == 0){
			return Result.createError("此用户没有绑定邮箱，请前往\"项目管理系统--个人档案\"中填写邮箱账号!");
		}
		User user = userList.get(0);
		if (!user.getEmail().endsWith("@jxthxr.com")){
			return Result.createError("请检查你在\"项目管理系统--个人档案\"中是否绑定的是公司内部邮箱且账号正确!");
		}
		return Result.createSuccess(user);
	}

	@Override
	public Integer changepwd(String account, String oldPassword, String newPassword) {
		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("account", account).andEqualTo("oldPassword", oldPassword);
		User user = new User();
		user.setPassword(newPassword);
		return userMapper.updateByExampleSelective(user, example);
	}
}
